package com.example.erhuo.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.erhuo.Good;
import com.example.erhuo.R;
import com.example.erhuo.api.NetAPI;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class GoodDetailActivity extends AppCompatActivity implements View.OnClickListener {
    private static String TAG = "GoodDetailActivity";

    private Good good;
    private TextView title;
    private TextView price;
    private TextView description;
    private TextView senderId;
    private ImageView image;

    private Button wantButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            actionBar.setCustomView(R.layout.title_layout);
            TextView textView = (TextView) actionBar.getCustomView().findViewById(R.id.display_title);
            textView.setText("商品详情");
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowCustomEnabled(true);
        }
        setContentView(R.layout.activity_good_detail);
        String goodId = getIntent().getStringExtra("goodId");
        initGood(goodId);
        initView();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initGood(String goodId) {
        RequestBody body = new FormBody.Builder()
                .add("goodid", goodId)
                .build();
        Callback callback = new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "获取商品信息失败");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String information = response.body().string();
                Log.i(TAG, information);
                JSONObject j;
                try {
                    j = new JSONObject(information);
                    String data = j.getString("data");
                    JSONObject jsonObject = new JSONObject(data);
                    String goodString = jsonObject.getString("good");
                    JSONObject object = new JSONObject(goodString);

                    String goodId = object.getString("goodid");
                    String goodStatus = object.getString("goodstatus");
                    String goodTitle = object.getString("goodname");
                    String goodDescription = object.getString("gooddescription");
                    String goodPrice = object.getString("goodprice");
                    String goodCategory = object.getString("goodcategory");
                    String goodSendTime = object.getString("goodsendtime");
                    String goodSenderId = object.getString("goodsenderid");

                    String goodPicUrl = null;
                    try {
                        goodPicUrl = object.getString("imagePATH");
                    } catch (Exception e) {
                        Log.e(TAG, "这个商品无图片");
                    }
                    Good tGood = new Good(goodTitle, goodPrice, goodDescription, goodCategory, goodSendTime, goodStatus, goodSenderId, goodId, goodPicUrl);
                    Callback callback = new Callback() {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                            tGood.setImage(null);
                        }

                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                            byte[] bytes = response.body().bytes();
                            Bitmap image = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                            tGood.setImage(image);
                        }
                    };
                    NetAPI.get("api/download/?path=" + goodPicUrl, callback, "");
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    good = tGood;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setView();
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        };
        NetAPI.postJsonWithToken("api/GoodOper/searchGoodWithId/", body, callback, MainActivity.token);

    }

    private void initView() {
        title = findViewById(R.id.detail_text_title);
        price = findViewById(R.id.detail_text_price);
        description = findViewById(R.id.detail_text_description);
        senderId = findViewById(R.id.detail_text_sender);
        image = findViewById(R.id.detail_image);
        wantButton = findViewById(R.id.detail_button_want);
    }

    private void setView() {
        title.setText(good.getTitle());
        price.setText("￥" + good.getPrice());
        description.setText(good.getDescription());
        senderId.setText(good.getSenderId());
        image.setImageBitmap(good.getImage());
       // Log.i(TAG, "" + good.getImage().getByteCount());
        wantButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.detail_button_want: {
                //Log.i(TAG, "here!!!");
                if (MainActivity.token == null || MainActivity.token.equals("")) {
                    Toast.makeText(getBaseContext(), "请先登录", Toast.LENGTH_SHORT).show();
                    wantButton.setClickable(false);
                    wantButton.setBackgroundColor(getResources().getColor(R.color.grey));
                    return;
                }
                RequestBody body = new FormBody.Builder()
                        .add("goodid", good.getId())
                        .build();
                Callback callback = new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), "添加失败，请检查网络", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String information = response.body().string();
                        Log.i(TAG, information);
                        JSONObject object;
                        try {
                            object = new JSONObject(information);
                            String code = object.getString("code");
                            String msg = object.getString("msg");
                            switch (msg) {
                                case "创建成功": {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            AlertDialog.Builder builder = new AlertDialog.Builder(GoodDetailActivity.this);
                                            builder.setTitle("添加成功");
                                            builder.setMessage("请在我的主页查询详情，并给出报价");
                                            builder.setPositiveButton("好的", null);
                                            builder.show();
                                            wantButton.setClickable(false);
                                            wantButton.setBackgroundColor(getResources().getColor(R.color.grey));
                                        }
                                    });
                                    Log.i(TAG, "想要成功");
                                    break;
                                }
                                case "不能想要自己发布的商品": {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getApplicationContext(), "不能想要自己发布的商品", Toast.LENGTH_SHORT).show();
                                            wantButton.setClickable(false);
                                            wantButton.setBackgroundColor(getResources().getColor(R.color.grey));
                                        }
                                    });
                                    break;
                                }
                                case "该商品已被喜欢": {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getApplicationContext(), "您已想要该商品", Toast.LENGTH_SHORT).show();
                                            wantButton.setClickable(false);
                                            wantButton.setBackgroundColor(getResources().getColor(R.color.grey));
                                        }
                                    });
                                    break;
                                }
                                default: {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getApplicationContext(), "您已想要该商品", Toast.LENGTH_SHORT).show();
                                            wantButton.setClickable(false);
                                            wantButton.setBackgroundColor(getResources().getColor(R.color.grey));
                                        }
                                    });
                                    break;
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };
                if (MainActivity.token != null) {
                    NetAPI.postJsonWithToken("api/OrderOper/like/", body, callback, MainActivity.token);
                } else {
                    NetAPI.postJsonWithToken("api/OrderOper/like/", body, callback, "");
                }
                break;
            }
        }
    }
}